<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>大文件断点续传</title>
</head>

<body>
  <script>
    // 大文件切片
    function sliceFile(file, chunkSize) {
      var chunks = [];
      var fileSize = file.size;
      var start = 0;

      while (start < fileSize) {
        var end = start + chunkSize;
        var chunk = file.slice(start, end);
        chunks.push(chunk);
        start = end;
      }

      return chunks;
    }

    var file = document.getElementById("fileInput").files[0];
    var chunkSize = 1024 * 1024; // 1MB
    var chunks = sliceFile(file, chunkSize);


    // 为每个文件生成唯一的id
    function generateChunkId(index) {
      return "chunk-" + index;
    }
    var chunkIds = chunks.map(function (chunk, index) {
      return generateChunkId(index);
    });

    // 上传文件块
    function uploadChunk(chunk, chunkId) {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "your_server_url");
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.setRequestHeader("X-Chunk-Id", chunkId);

        xhr.onload = function () {
          if (xhr.status === 200) {
            resolve();
          } else {
            reject(new Error("Upload failed: " + xhr.statusText));
          }
        };

        xhr.onerror = function () {
          reject(new Error("Network error"));
        };

        xhr.send(chunk);
      });
    }

    var uploadPromises = chunks.map(function (chunk, index) {
      var chunkId = chunkIds[index];
      return uploadChunk(chunk, chunkId);
    });

    Promise.all(uploadPromises)
      .then(function () {
        console.log("All chunks uploaded successfully");
      })
      .catch(function (error) {
        console.error("Failed to upload chunks:", error);
      });

    // 实现断点续传
    function getUploadedChunks() {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "your_server_url");
        xhr.responseType = "json";

        xhr.onload = function () {
          if (xhr.status === 200) {
            resolve(xhr.response);
          } else {
            reject(new Error("Failed to get uploaded chunks: " + xhr.statusText));
          }
        };

        xhr.onerror = function () {
          reject(new Error("Network error"));
        };

        xhr.send();
      });
    }

    getUploadedChunks()
      .then(function (uploadedChunkIds) {
        var remainingChunks = chunks.filter(function (chunk, index) {
          return !uploadedChunkIds.includes(chunkIds[index]);
        });

        // Upload remaining chunks
      })
      .catch(function (error) {
        console.error("Failed to get uploaded chunks:", error);
      });
  </script>
</body>

</html>